package cn.ciis.server.handler;

import cn.ciis.basic.TioHandlerInterface;
import cn.ciis.basic.base.BaseCache;
import cn.ciis.basic.kit.ByteKit;
import cn.ciis.basic.kit.J2CacheKit;
import cn.ciis.basic.plugin.CiisHandler;
import cn.ciis.basic.plugin.CiisSessionContext;
import cn.ciis.basic.websocket.AuthorityWebSocket;
import cn.ciis.server.CiisConstant;
import cn.ciis.server.CiisPacket;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import net.oschina.j2cache.CacheObject;

/**
 * 工作模式
 */
@TioHandlerInterface(order = 3)
public class OperatingModeHandler extends CiisHandler {

    AuthorityWebSocket authorityWebSocket= Aop.get(AuthorityWebSocket.class);

    @Override
    public void handle(CiisPacket ciisPacket, CiisSessionContext ciisSessionContext) {
        if( StrUtil.equalsIgnoreCase("5ad2", ByteKit.bytesToHexString(ciisPacket.getCmd()))){//判断是否是设备数据
            LogKit.info("接收到客户端发送过来的信息:{}",ByteKit.bytesToHexString(ciisPacket.getBody()));
            if(ciisSessionContext.getEquipment().isPresent()){
                byte[] body=ciisPacket.getBody();
                String bsId = ciisSessionContext.getBsId();
                issued(body, CiisConstant.AUTOMATIC_MODE,bsId,0,"工作模式切换成功");
                issued(body, CiisConstant.MANUAL_MODE,bsId,1,"启动成功");
                issued(body, CiisConstant.STOP_COMMAND,bsId,2,"停止成功");
                issued(body, CiisConstant.PAUSE_COMMAND,bsId,3,"暂停成功");
                //测试数据7e5ada000100015ad20004000105000d0d
            }
        }
    }


    public void issued(byte[] body,String command,String bsId,int type,String msg){
        String s = ByteKit.bytesToHexString(body);
        if (s.substring(0,6).equals(command)) {
            CacheObject cacheObject = J2CacheKit.get(BaseCache.WS_SESSION_ID_DICTIONARY, bsId + command);
            if(cacheObject !=null && cacheObject.getValue() !=null){

                Record record = new Record();
                record.set("type",type);
                record.set("currentValue",s.substring(7,8));

                authorityWebSocket.sendMsg(cacheObject.getValue().toString(), Ret.ok("msg",msg).set("category","issued").set("data", record).toJson());
                J2CacheKit.evict(BaseCache.WS_SESSION_ID_DICTIONARY,bsId+"command");
            }
        }
    }
}
